<?php
declare(strict_types=1);

namespace app\common\traits;

use app\common\model\Language as LanguageModel;
use think\facade\Request;

trait HasLanguage
{
    /**
     * 初始化语言特征
     */
    public static function initHasLanguage()
    {
        // 添加获取器
        $model = new self();
        if (isset($model->langFields)) {
            foreach ($model->langFields as $field) {
                static::defineLanguageGetter($field);
            }
        }
    }

    /**
     * 定义语言字段获取器
     * @param string $field
     */
    protected static function defineLanguageGetter(string $field)
    {
        $method = 'get' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $field))) . 'Attr';
        
        if (!method_exists(static::class, $method)) {
            static::macro($method, function ($value, $data) use ($field) {
                $langId = $this->getCurrentLanguageId();
                $langData = $this->langs()
                    ->where('language_id', $langId)
                    ->find();
                
                return $langData ? $langData->$field : $value;
            });
        }
    }

    /**
     * 获取当前语言ID
     * @return int
     */
    public static function getCurrentLanguageId(): int
    {
        $langCode = Request::header('Accept-Language') ?: 'zh-CN';
        $language = LanguageModel::where('code', $langCode)
            ->where('status', 1)
            ->find();
        
        return $language ? $language->language_id : 1; // 默认返回中文
    }

    /**
     * 转换为数组
     * @param array $data
     * @param bool $format
     * @return array
     */
    public function toArray(array $data = [], bool $format = true): array
    {
        $data = parent::toArray($data, $format);
        
        // 获取当前语言的数据
        $langId = $this->getCurrentLanguageId();
        $langData = $this->langs()
            ->where('language_id', $langId)
            ->find();
            
        // 填充语言字段
        if ($langData && isset($this->langFields)) {
            foreach ($this->langFields as $field) {
                $data[$field] = $langData->getAttr($field);
            }
        }

        return $data;
    }

    /**
     * 语言关联
     * 注意：这里需要在具体模型中实现
     */
    abstract public function langs();

    /**
     * 获取语言关联查询
     * @return \think\model\relation\HasMany
     */
    protected function getLanguageRelation()
    {
        return $this->langs()->with(['language' => function($query) {
            $query->field(['language_id', 'name', 'code', 'icon']);
        }]);
    }

    /**
     * 获取所有语言版本数据（包含语言信息）
     * @return array
     */
    public function getAllLangDataWithInfo()
    {
        $data = [];
        $langs = $this->getLanguageRelation()->select();

        foreach ($langs as $lang) {
            $data[$lang->language_id] = [
                'name' => $lang->name,
                'remark' => $lang->remark,
                'language' => [
                    'language_id' => $lang->language->language_id,
                    'name' => $lang->language->name,
                    'code' => $lang->language->code,
                    'icon' => $lang->language->icon
                ]
            ];
        }

        return $data;
    }
} 